package gosnoopers.fr;

import java.util.ArrayList;
import java.util.HashMap;

import lazy_listview.JSONfunctions;
import listview.CountriesAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import common.Common;
 
 
public class Countries extends Activity {
	static final String URL = "http://gosnoopers.com/country/getAllCountries";
	
	ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String ID = "id";
    static String NAME = "name";
    static String ALIAS = "alias";
    public static JSONObject jsonobject;
    public static JSONArray jsonarray;
    ListView list;
	
	CountriesAdapter adapter;
	
	public static String selectedCountry = "";
	public static String listCity = "";
	
	//**************************check connect****************
    public  boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    
    //************************create activity**********************
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          this.requestWindowFeature(Window.FEATURE_NO_TITLE);
          setContentView(R.layout.countries);
          
          header();
          
          String TextHeader = "Countries";
          TextView text = (TextView) findViewById(R.id.text_view_landing_page_header);
          text.setText(TextHeader);
          
	      if(!isNetworkAvailable()){
	    	  
	    	  Toast toast = Toast.makeText(getApplicationContext(), Common.MSG, Toast.LENGTH_SHORT);
	    	  toast.show();
	      }else{
	    	  new DownloadJSON().execute();
	      }
	      
			ImageView btn_setting = (ImageView) findViewById(R.id.image_setting);
			btn_setting.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent goToNextActivity = new Intent(getApplicationContext(), Settings.class);
		            startActivity(goToNextActivity);
				}
			});
	      
      }
      /*
       * **************************** set header ***************************
       */
      public void header() {
  		ImageView btn_setting = (ImageView) findViewById(R.id.image_setting);
  		btn_setting.setOnClickListener(new OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				Intent goToNextActivity = new Intent(getApplicationContext(),
  						Settings.class);
  				startActivity(goToNextActivity);
  			}
  		});

  		/**
  		 * Kiem user da dang nhap hay chua 1. hein thi icon user 2. hien thi
  		 * icon add victimes
  		 */
  		ImageView image_open_left_navigation = (ImageView) findViewById(R.id.image_open_left_navigation);
  		ImageView icon_header_form = (ImageView) findViewById(R.id.icon_header_form);
  		if (MainActivity.userId.equalsIgnoreCase("0")) {
  			image_open_left_navigation.setVisibility(View.VISIBLE);
  			icon_header_form.setVisibility(View.GONE);
  		} else {
  			image_open_left_navigation.setVisibility(View.GONE);
  			icon_header_form.setVisibility(View.VISIBLE);
  		}

  		image_open_left_navigation.setOnClickListener(new OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				Intent goToNextActivity = new Intent(getApplicationContext(),
  						MainActivity.class);
  				startActivity(goToNextActivity);
  			}
  		});

  		icon_header_form.setOnClickListener(new OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				Intent goToNextActivity = new Intent(getApplicationContext(),
  						FormFirst.class);
  				startActivity(goToNextActivity);
  			}
  		});
  	}
      
      
	   // *****************************DownloadJSON AsyncTask
	      private class DownloadJSON extends AsyncTask<Void, Void, Void> {
	   
	          @Override
	          protected void onPreExecute() {
	              super.onPreExecute();
	              ProgressBar mProBarLoading = (ProgressBar)findViewById(R.id.probar_loading);
	              mProBarLoading.setVisibility(View.VISIBLE);
	          }
	   
	          @Override
	          protected Void doInBackground(Void... params) {
	              // Create an array
	              arraylist = new ArrayList<HashMap<String, String>>();
	              // Retrieve JSON Objects from the given URL address
	              
	              jsonobject = JSONfunctions.getJSONfromURL(URL);
	              try {
	                  // Locate the array name in JSON
	                  jsonarray = jsonobject.getJSONArray("data");
	                  boolean strError = jsonobject.getBoolean("error");
	                  String message = jsonobject.getString("message");
	                  if(!strError){
	                  	for (int i = 0; i < jsonarray.length(); i++) {
	                          HashMap<String, String> map = new HashMap<String, String>();
	                          jsonobject = jsonarray.getJSONObject(i);
	                          // Retrive JSON Objects
	                          map.put("id", jsonobject.getString("Id"));
	                          map.put("name", jsonobject.getString("Name"));
	                          map.put("alias", jsonobject.getString("Alias"));
	                          
	                          // Set the JSON Objects into the array
	                          arraylist.add(map);
	                      }
	                  	
	                  }else{
	                  	Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
	        	    	  	toast.show();
	                  }
	                  
	              } catch (JSONException e) {
	                  Log.e("Error", e.getMessage());
	                  e.printStackTrace();
	              }
	              return null;
	          }
	   
	          @Override
	          protected void onPostExecute(Void args) {
	              // Locate the listview in listview_main.xml
	        	  ProgressBar mProBarLoading = (ProgressBar)findViewById(R.id.probar_loading);
	              mProBarLoading.setVisibility(View.GONE);
	          	list = (ListView) findViewById(R.id.list);
	              // Pass the results into ListViewAdapter.java
	              adapter = new CountriesAdapter(Countries.this, arraylist);
	              // Set the adapter to the ListView
	              list.setAdapter(adapter);

	              list.setOnItemClickListener(new OnItemClickListener() {



	  				@Override
	  				public void onItemClick(AdapterView<?> arg0, View view,
	  						int position, long id) {
	  					// TODO Auto-generated method stub
	  	                 // ListView Clicked item index
	  	                 int itemPosition     = position;
	  	                 
	  	                  TextView id_country = (TextView) view.findViewById(R.id.id_country);
	  	                TextView name = (TextView) view.findViewById(R.id.name);
	  	                    
	  	                  // Show Alert selectedCountry 
	  	                  /*Toast.makeText(getApplicationContext(),
	  	                    "Position :"+itemPosition+"  ListItem :  - "+id_country.getText()+ " -- " +id, Toast.LENGTH_LONG)
	  	                    .show();*/
	  	                Intent goToNextActivity = new Intent(getApplicationContext(), Cities.class);
						goToNextActivity.putExtra("ID_COUNTRY", id_country.getText());
						goToNextActivity.putExtra("COUNTRY_NAME", name.getText());
		               startActivity(goToNextActivity);
	  					
	  				}

	              }); 
	          }
	      }
}